package com.zlx.store.goods.service.impl;

import com.zlx.store.domain.entity.Goods;
import com.zlx.store.domain.entity.GoodsCategory;
import com.zlx.store.domain.entity.Store;
import com.zlx.store.domain.vo.GoodsVo;
import com.zlx.store.goods.dao.GoodsCategoryDao;
import com.zlx.store.goods.dao.GoodsDao;
import com.zlx.store.goods.dao.StoreDao;
import com.zlx.store.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * (Goods)表服务实现类
 *
 * @author makejava
 * @since 2023-07-29 17:11:43
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    GoodsCategoryDao goodsCategoryDao;
    @Autowired
    StoreDao storeDao;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param goodsId 主键
     * @return 实例对象
     */
    @Override
    public Goods queryById(Long goodsId) {
        return goodsDao.selectById(goodsId);
    }
    @Override
    public GoodsVo detail(Long goodsId) {
        Goods goods=goodsDao.selectById(goodsId);
        String goodsCategory=(String) redisTemplate.opsForHash().get("category",String.valueOf(goods.getGoodsCategory()));
        String store=(String) redisTemplate.opsForHash().get("store",String.valueOf(goods.getGoodsStoreId()));
        double weekSale=0.0;
        if (Objects.nonNull(redisTemplate.opsForZSet().score("hotGoods_manual",goodsId))){
            weekSale=redisTemplate.opsForZSet().score("hotGoods_manual",goodsId);
        }
        if (Objects.nonNull(redisTemplate.opsForZSet().score("hotGoods_auto",goodsId))){
            weekSale=redisTemplate.opsForZSet().score("hotGoods_auto",goodsId);
        }
        GoodsVo goodsVo=new GoodsVo(goods,goodsCategory,store,weekSale);
        return goodsVo;
    }


    /**
     * 新增数据
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @Override
    public Goods insert(Goods goods) {
        goodsDao.insert(goods);
        return goods;
    }

    /**
     * 修改数据
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @Override
    public Goods update(Goods goods) {
        goodsDao.updateById(goods);
        return this.queryById(goods.getGoodsId());
    }

    /**
     * 通过主键删除数据
     *
     * @param goodsId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long goodsId) {
        return goodsDao.deleteById(goodsId) > 0;
    }
}
